<template>
  <div class="app-container">
    <el-container style="height: 500px; border: 1px solid #eee">
      <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
        <el-menu :default-openeds="['1', '12']">
          <el-submenu index="1">
            <template slot="title"><i class="el-icon-message"></i>用户列表</template>
            <el-menu-item-group>
              <el-menu-item
                v-for="(item, index) in userList"
                :key="index"
                :index="index + ''"
                @click="switchUsers(item.ip)"
                :class="currentUser === item.ip ? 'onSelect' : ''"
              >
                <el-badge
                  :hidden="item.unreadNum == 0 ? true : false"
                  :value="item.unreadNum"
                  :max="99"
                  class="item"
                >
                </el-badge>
                <span :class="item.status ? 'status-online' : 'status'">{{
                  item.ip
                }}</span>
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-aside>

      <el-container>
        <!-- <el-header style="height: 20px; text-align: center; font-size: 15px">
          <p class="currentUser">{{ currentUser }}</p>
        </el-header> -->

        <el-main style="text-align: center; overflow: hidden">
          <div class="message-record">
            <div class="msg-box">
              <div
                v-for="(item, i) in messageList"
                :key="i"
                :class="[item.fromUser === message.fromUser ? 'right' : 'left']"
              >
                <p>{{ item.time }}</p>
                <p class="msg" v-html="item.msg || item.message"></p>
              </div>
            </div>
            <div class="msg-input">
              <!-- <editor v-model="textarea" :height="60" /> -->
              <el-input
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入内容"
                type="textarea"
                v-model="textarea"
              >
              </el-input>
            </div>
            <div class="submit-msg">
              <el-button type="primary" size="medium" @click="submitMsg">
                发送消息
              </el-button>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
export default {
  name: "OnlineChat",
  data() {
    return {
      drawer: false,
      messageList: [],
      message: {
        //你的id
        fromUser: "server",
        //发给哪个用户 id
        toUser: null,
        //消息载体
        msg: null,
        time: "",
      },
      ws: null,
      userList: [],
      //当前用户
      currentUser: "",
      textarea: "",
    };
  },
  watch: {
    currentUser(newval, oldval) {
      // console.log(newval);
      if (newval != "") {
        let arr = this.userList.find((obj) => obj.ip === newval);
        this.messageList = arr.historyMsg;
        arr.unreadNum = 0;
      }
    },
  },
  methods: {
    //发送消息
    submitMsg() {
      this.message.toUser = this.currentUser;
      this.message.msg = this.textarea;
      this.message.time = this.dateFromat();

      // send 方法给服务端发送消息
      this.ws.send(JSON.stringify(this.message));

      this.textarea = "";
    },
    switchUsers(item) {
      this.currentUser = item;
    },
    dateFromat() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let d = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let second = date.getSeconds();

      if (month < 10) {
        month = "0" + month;
      }

      if (d < 10) {
        d = "0" + d;
      }

      if (hour < 10) {
        hour = "0" + hour;
      }

      if (minute < 10) {
        minute = "0" + minute;
      }

      if (second < 10) {
        second = "0" + second;
      }

      return year + "-" + month + "-" + d + " " + hour + ":" + minute + ":" + second;
    },
  },
  created() {
    this.ws = new WebSocket(`ws://localhost:5555/websocket/${this.message.fromUser}`);
    // this.ws = new WebSocket(
    //   `wss://admin.yssw-gz.com:443/websocket/${this.message.fromUser}`
    // );
    //这里做连接服务器
    this.ws.onopen = () => {};
  },
  mounted() {
    this.ws.onmessage = (res) => {
      let msg = JSON.parse(res.data);
      console.log(msg);
      if (msg.userList != undefined) {
        this.userList = msg.userList;
        for (let i = 0; i < this.userList.length; i++) {
          if (this.userList[i].ip === this.currentUser) {
            this.userList[i].unreadNum = 0;
            this.messageList = this.userList[i].historyMsg;
          }
        }
      }
    };
    //异常处理
    // 监听连接失败
    this.ws.onerror = () => {
      console.log("连接失败，正在重连...");
      this.ws.onopen = () => {};
    };
  },
};
</script>

<style scoped>
.message-record {
  position: relative;
  width: 100%;
  height: 100%;
  border: 3px #409eff solid;
  border-radius: 10px;
}
.divider {
  position: absolute;
  width: 100%;
  height: 1px;
  bottom: 27%;
  background-color: #409eff;
}

.submit-msg {
  position: absolute;
  right: 50px;
  bottom: 40px;
}
.msg-input {
  position: absolute;
  width: 80%;
  bottom: 0;
  left: 1%;
  height: 26%;
}
.msg-box {
  position: absolute;
  width: 97%;
  height: 70%;
  border: rgba(102, 100, 100, 0.303) 1px solid;
  margin: 10px;
  overflow: auto;
}

.left {
  text-align: left;
  padding-left: 20px;
}
.right {
  text-align: right;
  padding-right: 20px;
}
.msg {
  text-align: left;
  word-break: break-all;
  border-radius: 4px;
  border-radius: 8px 0 8px 8px;
  background: rgba(100, 147, 252, 0.16);
  line-height: 22px;
  display: inline-block;
  max-width: 80%;
  padding: 12px;
  font-size: 14px;
  margin-top: 0;
}
.status {
  color: gray;
  text-align: left;
}

.status-online {
  color: rgb(51, 251, 20);
  text-align: left;
}
.item {
  position: absolute;
  margin-left: 75px;
}
.onSelect {
  background-color: #32a2da;
}
</style>
